/*
 * jenkins.c
 *
 *  Created on: Feb 12, 2012
 *      Author: daniel
 */

#include "jenkins.h"
#include "pollerutils.h"
#include "../cJSON.h"
#include "../renderers/build.h"
#include <glib.h>

#include <string.h>
#include <stdlib.h>

#define STATUS_BLUE "blue"
#define STATUS_RED "red"
#define STATUS_RED_ANIME "red_anime"
#define STATUS_BLUE_ANIME "blue_anime"

#define JOBS "jobs"
#define JOB_NAME "name"
#define JOB_COLOR "color"

static GHashTable* builds;

static void create() {
	builds = g_hash_table_new(g_str_hash, g_str_equal);
}

static void dispose() {
	g_hash_table_remove_all(builds);
	g_hash_table_destroy(builds);
}

static void poll() {

	expandinglump_t chunk;
	pollerutils_httpget("http://192.168.2.253:8080/api/json", &chunk);

	printf("%s\n", chunk.memory);

	cJSON* root = cJSON_Parse(chunk.memory);
	if (root != NULL) {
		cJSON* jobs = cJSON_GetObjectItem(root, JOBS);
		if (jobs != NULL) {
			for (cJSON* job = jobs->child; job != NULL; job = job->next) {
				cJSON* name = cJSON_GetObjectItem(job, "name");
				cJSON* color = cJSON_GetObjectItem(job, "color");
				build_t* build = g_hash_table_lookup(builds, name->valuestring);

				if (strcmp(color->valuestring, STATUS_BLUE) == 0) {
					if (build != NULL) {
						g_hash_table_remove(builds, build);
					}
					continue;
				}

				if (build == NULL) {
					build = malloc(sizeof(build));
					build->name = malloc(strlen(name->valuestring) + 1);
					strcpy(build->name, name->valuestring);
					g_hash_table_insert(builds, build->name, build);
				}

				if (strcmp(color->valuestring, STATUS_RED) == 0) {
					build->status = FAILED;
				}
				else if (strcmp(color->valuestring, STATUS_RED_ANIME) == 0) {
					build->status = FAILED_BUILDING;
				}
				else if (strcmp(color->valuestring, STATUS_BLUE_ANIME) == 0) {
					build->status = OK_BUILDING;
				}

				printf("%s %s\n", name->valuestring, color->valuestring);

			}
		}
		cJSON_Delete(root);
		free(chunk.memory);
	}
	else {
		printf("seems cJSON couldnt parse the json\n");
	}

}

poller_t jenkinspoller = { NULL, create, NULL, poll, dispose };
